﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//添加类似于List<T>类的ForEach(Action<T> action)方法,通过调用这个方法打印链表元素，求最大值、最小值和求和（使用lambda表达式实现）
public class Node<T>
{
    public Node<T> Next { get; set; }
    public T Data { get; set; }
    public Node(T t)
    {
        Next = null;
        Data = t;
    }
}
public class GenericList<T>
{
    private Node<T> head;
    private Node<T> tail;

    public GenericList() //默认构造函数
    { tail = head = null; }
    public Node<T> Head
    { get => head; }
    public void Add(T t)
    {
        Node<T> n = new Node<T>(t);
        if (tail == null)
        {
            head = tail = n;
        }
        else
        {
            tail.Next = n;
            tail = n;
        }
    }

    //ForEach函数，Action泛型委托类型：
    public void ForEach(Action<T> action)
    {
        Node<T> curr = head;
        while (curr != null)
        {
            action(curr.Data);
            curr = curr.Next;
        }
    }
}
namespace GenList
{
    internal class Program
    {
        static void Main(string[] args)
        {
            GenericList<int> list = new GenericList<int>();
            list.Add(10);
            list.Add(5);
            list.Add(3);
            list.Add(7);
            list.Add(-10);

            //打印链表元素：
            Console.WriteLine("链表里面的元素有：");
            list.ForEach(x => Console.WriteLine(x));

            //最大值：
            int max = int.MinValue;
            list.ForEach(x => { if (x > max) max = x; });
            Console.WriteLine($"最大值是：{max}");

            //最小值：
            int min = int.MaxValue;
            list.ForEach(x => { if (x < min) min = x; });
            Console.WriteLine($"最小值是：{min}");

            //求和：
            int sum = 0;
            list.ForEach(x => sum += x);
            Console.WriteLine($"和是：{sum}");
            Console.ReadLine();
        }
    }
}
